"use strict";
const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCssAssetsWebpackPlugin = require("optimize-css-assets-webpack-plugin");

module.exports = {
  mode: "production",
  entry: {
    index: "./src/index.js",
    search: "./src/search.js",
  },
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "[name]_[chunkhash:8].js",
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        use: "babel-loader",
      },
      // 解析css,less,sass
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, "css-loader", "postcss-loader",{
          loader: "px2rem-loader",
          options: {
            remUnit: 75,
            remPrecision: 8
          }
        }], // 链式调用，从右到左实际执行先用css-loader解析css再传递给style-loader
      },
      {
        test: /\.less$/,
        use: ["style-loader", "css-loader", "less-loader"], // 链式调用，从右到左实际执行先用css-loader解析css再传递给style-loader
      },
      // file-loader解析图片、字体文件
      // {
      //   test: /\.(png|gif|jpg|jpeg)$/,
      //   use: [
      //     {
      //       loader: "url-loader",
      //       options: {
      //         limit: 20480, // url-loader处理图片和字体 可以设置较小资源自动base64(小于设置的limit自动转为base64)
      //       },
      //     },
      //   ],
      // },
      {
        test: /\.(png|gif|jpg|jpeg)$/,
        use: [
          {
            loader: "file-loader",
            options: {
              name: "img/[name][hash:8].[ext]",
            },
          },
        ],
      },
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/,
        use: "file-loader",
      },
    ],
  },
  plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      title: "Hot Module Replacement",
      template: "./index.html",
      chunks: ["app"],
      inject: true, //js，css自动注入HTML
      minify: {
        //压缩相关
        html5: true,
        collapseWhitespace: true,
        minifyCSS: true,
        minifyJS: true,
      },
    }),
    new MiniCssExtractPlugin({ filename: "[name]_[contenthash:8].css" }),
    new OptimizeCssAssetsWebpackPlugin({
      assetNameRegExp: /\.css$/,
      cssProcessor: require("cssnano"),
    }),
  ],
  devtool: 'source-map',
  devServer: {
    contentBase: "./dist",
    hot: true,
  },
};
